﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lm.Common.Auth.Role
{
    class ValidateRoleOperationPermission
    {
        public void Validate(Guid tokenOwnerAccountId,Guid tokenOperatorAccountId , Guid operationId)
        {
            if (tokenOwnerAccountId == null)
            { throw new Exception("accountId不能为空"); }
            if (operationId == null)
            { throw new Exception("operationId不能为空"); }
            using (var tran = new System.Transactions.TransactionScope())
            {
                var helper = Lm.Common.Auth.DAL.DALFactory.Create();
                //当操作人员和权限所有人不是同一个人时,检查操作员帐号状态
                if (tokenOwnerAccountId != tokenOperatorAccountId)
                {
                    new Account.AccountValidator().Validate(tokenOperatorAccountId);
                }
                //检查授权软人帐号状态
                var tokenOwnerAccount = new Account.AccountValidator().Validate(tokenOwnerAccountId);               

                if (helper.IsSingle<Model.Role>(t => t.RoleId == tokenOwnerAccount.RoleId) == false)
                { throw new Exception("角色不存在：" + tokenOwnerAccount.RoleId); }
                var role = helper.GetSingle<Model.Role>(t => t.RoleId == tokenOwnerAccount.RoleId);
                if (role.GetRoleStatus() !=  Model.RoleStatus.Live)
                { throw new Exception("角色不是可用状态" ); }
                if (role.Pause)
                { throw new Exception("角色处于暂停状态"); }
                if (helper.IsSingle<Model.RolePermission>(t => t.RoleId == role.RoleId && t.OperationId == operationId) == false)
                { throw new Exception("没有权限"); }
                if (helper.IsSingle<Model.Operation>(t => t.Id == operationId) == false)
                { throw new Exception("权限不存在"); }
                var operation = helper.GetSingle<Model.Operation>(t => t.Id == operationId);
                if (operation.Status != Model.OperationStatus.Live.ToString())
                { throw new Exception("权限不是可用状态"); }
                if (operation.Pause)
                { throw new Exception("权限处于暂停状态"); }
                tran.Complete();
            }
        }
    }
}
